package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.service.MqOpService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Component
@Slf4j
public class AlbumInfoReceiver {
    @Autowired
    private MqOpService mqOpsService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true", exclusive = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE))
    @SneakyThrows   // 可以绕开编译期间的异常 等运行时发现异常才抛出
    public void listenAlbumAndTrackStatNumUpdate(String content, Message message, Channel channel) {
//        content = null;

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        if (!StringUtils.hasText(content)) {
            channel.basicNack(deliveryTag, false, false);
            throw new GuiguException(201, "消息为空");
        }
        TrackStatMqVo trackStatMqVo = JSONObject.parseObject(content, TrackStatMqVo.class);
        try {
            mqOpsService.listenAlbumAndTrackStatNumUpdate(trackStatMqVo);
            channel.basicAck(deliveryTag, false);
        } catch (GuiguException e) {
            // 重试消息消费
            String retryMsgKey = "retry:msg:" + trackStatMqVo.getBusinessNo();
            Long count = redisTemplate.opsForValue().increment(retryMsgKey);
            if (3 >= count) {
                log.error("消息重试了{}次", count);
                channel.basicNack(deliveryTag, false, true);
            } else {
                log.error("消息重试了{}次，异常原因：{}，请人工排查", count, e.getMessage());
                channel.basicNack(deliveryTag, false, false);
            }
        } catch (Exception e) {
            log.error("手动应答期间，网络出现了抖动，但是业务已经被成功执行过，消息直接丢掉");
            channel.basicNack(deliveryTag, false, false);
        }
    }
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_ALBUM_STAT_UPDATE, durable = "true", exclusive = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = MqConst.ROUTING_ALBUM_STAT_UPDATE))
    @SneakyThrows   // 可以绕开编译期间的异常 等运行时发现异常才抛出
    public void listenAlbumAndBuyNumUpdate(String orderInfoStr, Message message, Channel channel) {
        // 1.获取消息，进行判断
        if (!StringUtils.hasText(orderInfoStr)) {
            return;
        }

        // 2.消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        OrderInfo orderInfo = JSONObject.parseObject(orderInfoStr, OrderInfo.class);
        try {
            mqOpsService.updateAlbumAndBuyNum(orderInfo);
            // 3.手动应答
            channel.basicAck(deliveryTag, false);
        } catch (GuiguException e) {
            // 重试 消息继续能够被消费者消费

            String retryMsgKey = "retry:msg:" + orderInfo.getOrderNo();
            Long count = redisTemplate.opsForValue().increment(retryMsgKey);
            if (count >= 3) {
                log.error("消息重试了{}次，异常原因：{}，请人工排查", count, e.getMessage());
                channel.basicNack(deliveryTag, false, false);  // 删除掉
            } else {
                log.error("消息重试了{}次", count);
                channel.basicNack(deliveryTag, false, true);
            }
        } catch (Exception e) {
            log.error("手动应答期间，网络出现了抖动，但是业务已经被成功执行过，消息直接丢掉");
            channel.basicNack(deliveryTag, false, false);
        }

    }
}
